package dsx.mongo;

import java.util.HashMap;

import org.bson.Document;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.DBCollection;
import com.mongodb.client.MongoCollection;

import dsx.console.DsxConsole;
import dsx.log.ServLog;

public class MongoExcutor {

	private static HashMap<String, MongoDrv> drivers = new HashMap<String, MongoDrv>();
	private static ObjectMapper mapper = new ObjectMapper();
	private static Object connLock = new Object();

	public static MongoCollection<Document> getCollection(String serverName, String dbName, String collectionName) {
		synchronized (connLock) {
			try {
				if (drivers.containsKey(serverName)) {
					MongoDrv drv = drivers.get(serverName);
					return drv.getCollection(dbName, collectionName);
				}
				MongoDrv drv = new MongoDrv(serverName);
				drivers.put(serverName, drv);
				return drv.getCollection(dbName, collectionName);
			} catch (Exception ex) {
				DsxConsole.out(ex.getMessage(), "mongo tool, server:" + serverName + ",collection:" + collectionName,
						ServLog.error);
				return null;
			}
		}
	}

	public static DBCollection getDBCollection(String serverName, String dbName, String collectionName) {
		synchronized (connLock) {
			try {
				if (drivers.containsKey(serverName)) {
					MongoDrv drv = drivers.get(serverName);
					return drv.getDBCollection(dbName, collectionName);
				}
				MongoDrv drv = new MongoDrv(serverName);
				drivers.put(serverName, drv);
				return drv.getDBCollection(dbName, collectionName);
			} catch (Exception ex) {
				DsxConsole.out(ex.getMessage(), "mongo tool, server:" + serverName + ",collection:" + collectionName,
						ServLog.error);
				return null;
			}
		}
	}

	public static Document objToBson(Object obj) {
		String json = objToJson(obj);
		if (json != "")
			return Document.parse(json);
		return null;
	}

	public static Object bsonToObj(Document bson, Class<?> type) {
		String json = bson.toJson();
		return jsonToObj(json, type);
	}

	private static Object jsonToObj(String str, Class<?> type) {
		try {
			return MongoExcutor.mapper.readValue(str, type);
		} catch (Exception ex) {
			return null;
		}
	}

	private static String objToJson(Object obj) {
		try {
			return MongoExcutor.mapper.writeValueAsString(obj);
		} catch (Exception ex) {
			return "";
		}
	}

}
